package web;

import ejb.CategoryBeanLocal;
import entities.Category;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.model.DefaultMenuModel;
import org.primefaces.model.MenuModel;

@ManagedBean(name = "utilsBean")
@SessionScoped
public class UtilsBean implements Serializable {

    @EJB
    private CategoryBeanLocal categoryBean;
    private List<Category> categories;
    private MenuModel model;

    public UtilsBean() {
    }

    @PostConstruct
    public void init() {
        categories = categoryBean.findAllVisible();
    }

    public MenuModel getModel() {
        if (model == null) {
            initModel();
        }
        return model;
    }

    public void setModel(MenuModel model) {
        this.model = model;
    }

    public void initModel() {
        model = new DefaultMenuModel();

        FacesContext context = FacesContext.getCurrentInstance();
        for (Category category : categories) {
            MenuItem categoryItem = new MenuItem();
            categoryItem.setId("categ" + category.getId().toString());
            categoryItem.setValue(category.getName());
            categoryItem.setAjax(false);
            categoryItem.setActionExpression(
                    context.getApplication().getExpressionFactory().createMethodExpression(
                    context.getELContext(), "main.xhtml", String.class, new Class[]{}));
            UIParameter param = new UIParameter();
            param.setName("category");
            param.setValue(category.getId());
            categoryItem.getChildren().add(param);

            model.addMenuItem(categoryItem);
        }
        setModel(model);
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }
}
